package platform.resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import platform.Platform;
import platform.config.*;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ResMgrThread implements Runnable {
    private static ResMgrThread instance;
    private static Thread t;
    private final Log logger = LogFactory.getLog(ResMgrThread.class);
    private static Map<String, SensorMgr> sensorMgrs = new HashMap<>();
    private static Map<String, ActorMgr> actorMgrs = new HashMap<>();

    // 构造方法私有化
    private ResMgrThread() {
    }

    // 静态方法返回该实例
    public static ResMgrThread getInstance() {
        // 第一次检查instance是否被实例化出来，如果没有进入if块
        if (instance == null) {
            synchronized (ResMgrThread.class) {
                // 某个线程取得了类锁，实例化对象前第二次检查instance是否已经被实例化出来，如果没有，才最终实例出对象
                if (instance == null) {
                    instance = new ResMgrThread();
                }
            }
        }
        return instance;
    }

    @Override
    public void run() {
        Platform.incrMgrStartFlag();

        Platform.lockUntilMgrStartFlagEqual(3);

        try {
            ServerSocket serverSocket = new ServerSocket(Configuration.getTcpConfig().getResourceListenPort());
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new ResourceDriver(socket)).start();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public static Map<String, SensorMgr> getSensorMgrs() {
        return sensorMgrs;
    }

    public static  Map<String, ActorMgr> getActorMgrs() {
        return actorMgrs;
    }

    public void start() {
        if (t == null) {
            t = new Thread(this, "ResMgrThread");
            t.start();
        }
    }
}
